<template>
  <div class="flexContent">
    <h3>调拨信息</h3>
    <div class="inner">
      <el-form ref="ruleForm" :disabled="detail.isDetail" :model="sform" :rules="rules" label-width="100px">
        <el-row :gutter="24">
          <el-col :span="10">
            <el-form-item label="出库门店：" prop="allocationStore">
              <el-select @click.native="getShopEasy" v-model="sform.allocationStore" popper-class="eloption" clearable
                style="width: 70%" filterable placeholder="选择门店">
                <el-option v-for="shop in shopList" :key="shop.id" :value="shop.id"
                  :disabled="shop.id == sform.receiveStore" :label="shop.name" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="入库门店：" prop="receiveStore">
              <el-select @click.native="getShopEasy" v-model="sform.receiveStore" popper-class="eloption" clearable
                style="width: 70%" filterable placeholder="选择门店">
                <el-option v-for="shop in shopList" :key="shop.id" :disabled="shop.id == sform.allocationStore"
                  :value="shop.id" :label="shop.name" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="20">
            <el-form-item label="备注：">
              <el-input v-clearEmoji v-model.trim="sform.remark" placeholder="最多输入50个字符" maxlength="50" show-word-limit
                style="width: 90%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="add" v-if="detail.isDetail">
      <!-- <el-button class="addBtn" @click="toAddPage" v-has="'allocation_add'">新增</el-button> -->
      <el-button class="addBtn" @click="exportFn" v-has="'allocation_export'">导出</el-button>
    </div>
    <div class="table">
      <el-form ref="formData" :model="formData" @submit.native.prevent>
        <el-table border class="tablebox" :data="formData.tableData" max-height="552" style="width: 100%" size="medium">
          <el-table-column align="center" type="index" label="序号" width="80" />
          <el-table-column align="center" prop="commodityName" label="商品名称"
            :min-width="elTableAdaptationWidth('commodityName', formData.tableData)">
            <template slot-scope="scope">
              <span v-if="detail.isDetail || scope.row.barCode">{{
                scope.row.commodityName
              }}</span>
              <el-form-item v-if="!detail.isDetail && !scope.row.barCode" :prop="'tableData.' + scope.$index + '.name'">
                <el-popover ref="myPopover" v-model="dialogVisible" placement="bottom-start" width="800" trigger="manual"
                  @show="openPopover" popper-class="remove-popover">
                  <el-table ref="popTab" border size="medium" height="300" :data="gridData1" class="tablebox"
                    highlight-current-row @row-click="handleCurrentChanges">
                    <el-table-column align="center" type="index" label="序号" width="80" />
                    <el-table-column align="center" property="commodityName" label="商品名称" />
                    <el-table-column align="center" property="barCode" label="商品条码" />
                    <el-table-column align="center" property="commodityStandard" label="规格" />
                    <el-table-column align="center" property="unitName" label="单位" />
                  </el-table>
                  <div class="pagination">
                    <el-pagination :current-page="page.pageNum" :page-sizes="$pageSizes" :page-size="page.pageSize"
                      background layout="total, ->,sizes, prev, pager, next, jumper" :total="page.total"
                      @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                  </div>
                  <el-input v-clearEmoji slot="reference" ref="inputaldQty" v-model.trim="scope.row.name"
                    placeholder="请输入..." class="group-inp" size="small" style="width: 100%"
                    @keyup.enter.native="getGoodsInfo(scope.row.name)" @input.enter.native="hiddenPop"/>
                </el-popover>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="barCode" label="商品条码" min-width="130" />
          <el-table-column align="center" prop="commodityStandard" label="规格" />
          <el-table-column align="center" prop="unitName" label="单位" />
          <el-table-column align="center" prop="commodityPacking" label="大包装" />
          <el-table-column align="center" prop="inventoryNumber" label="可调数量" v-if="!detail.isDetail" />
          <el-table-column align="center" prop="batchNumber" label="批次号"
            :min-width="elTableAdaptationWidth('batchNumber', formData.tableData)" />
          <el-table-column align="center" prop="allocationCount" label="调拨数量" show-overflow-tooltip min-width="180">
            <template slot-scope="scope">
              <el-form-item v-if="!detail.isDetail && scope.row.barCode"
                :prop="'tableData.' + scope.$index + '.allocationCount'"
                :rules="tableRules(formData.tableData[scope.$index])">
                <el-input v-clearEmoji ref="inputald" v-model.number.number="scope.row.allocationCount" placeholder=""
                  class="group-inp" size="small" style="width: 100%" @keyup.enter.native="nextInput" />
              </el-form-item>
              <span v-if="detail.isDetail">{{
                scope.row.allocationCount
              }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="!detail.isDetail" align="center" label="操作">
            <template v-if="!detail.isDetail && scope.row.barCode" slot-scope="scope">
              <el-button type="text" style="color: red"
                @click="delRegionByIndex(scope.$index, scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <div class="returnBtn">
      <el-button class="celBtn" v-if="!detail.isDetail" @click="cancelBtn">取消</el-button>
      <el-button class="celBtn" v-if="detail.isDetail" @click="cancelBtn">返回</el-button>
      <el-button class="addBtn" v-if="!detail.isDetail" @click="submitData('formData')">确定</el-button>
    </div>
    <goodsDialog ref="goodsDialogRef" :show-dialog.sync="showDialog" :grid-data2="gridData2" @commitFn="commitFn" />
  </div>
</template>

<script>
import FileSaver from 'file-saver'
import { getShopEasy, searchGoodsList, getBatchList, createAllocation, getAllocationDetail, exportAllocationList } from '@/api/shop';
import GoodsDialog from "./components/goodsDialog";
export default {
  name: "PurchaseBackAdd",
  components: {
    GoodsDialog,
  },
  watch: {
    formData: {
      handler(newVal, oldVal) {
        this.page = {
          pageNum: 1,
          pageSize: 20,
          total: 0,
        };
        console.log(this.page);
      },
      deep: true,
    },
  },
  data() {
    return {
      dialogTableVisible: false,
      dialogVisible: false,
      firstSupplierList: [],
      sform: {
        allocationStore: "", // 调拨门店ID
        receiveStore: '',  // 接收门店ID
        remark: "", // 备注
        detailsList: [],
      },
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      },
      rules: {
        allocationStore: [
          { required: true, message: "请选择调拨门店", trigger: "change" },
        ],
        receiveStore: [
          { required: true, message: "请选择接收门店", trigger: "blur" },
        ],
      },
      formData: {
        buyRemake: "",
        warehouseName: "",
        warehouseId: "",
        tableData: [{ name: "" }],
      },
      gridData1: [],
      gridData2: [],
      detail: {
        isDetail: false,
        id: "",
      },
      showDialog: false,
      goodsName: "",
      shopList: [],
      storeId: '',

      defaultRowKey: 0
    };
  },
  created() {
    this.getShopEasy()
    this.detail.id = this.$route.query.id;
    this.detail.isDetail = !!this.$route.query.id;
    if (this.detail.isDetail) {
      // 获取详情
      this.getAllocationDetail();
    }
  },
  watch: {
    dialogVisible(newValue, oldValue) {
      if (!newValue) document.removeEventListener('keyup', this.keyUp);
    }
  },
  methods: {
    async getShopEasy() {
      const res = await getShopEasy();
      if (res.code === 200) {
        console.log(res);
        const result = res.data;
        console.log('shopList', result);
        this.shopList = result.store;
        console.log('shopList', this.shopList);
      } else {
        // this.$message.error(res.message);
      }
    },
    async getAllocationDetail() {
      // console.log(this.detail.id, 'id')
      const res = await getAllocationDetail({ id: this.detail.id });
      if (res.code === 200) {
        console.log(res.data, "详情");
        this.sform.allocationStore = res.data.allocationStore;
        this.sform.receiveStore = res.data.receiveStore;
        this.sform.remark = res.data.remark;
        this.formData.tableData = res.data.detailsList;
      }
      console.log(res);
    },
    submitData(formName) {
      if (this.sform.allocationStore === this.sform.receiveStore) {
        return this.$message.warning('调拨门店和接收门店不能相同')
      }
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.formData.tableData.length <= 1)
            return this.$message.warning("请先选择要调拨的商品");
          this.$refs.formData.validate(async (valid) => {
            if (valid) {
              console.log(this.formData, "formData");
              this.sform.detailsList = [];
              this.formData.tableData.forEach((item) => {
                if (item.id && item.allocationCount) {
                  this.sform.detailsList.push({
                    inboundDetailsId: item.id,
                    allocationCount: item.allocationCount,
                  });
                }
              });
              // console.log(this.sform.detailsList, "this.sform");
              // return
              const res = await createAllocation({
                allocationStore: this.sform.allocationStore,
                receiveStore: this.sform.receiveStore,
                remark: this.sform.remark,
                detailsList: this.sform.detailsList,
              });
              if (res.code === 200) {
                this.$message.success("创建成功");
                this.closeTag("receiving");
              } else {
                // this.$message.error(res.message);
              }
            }
          });
        }
      });
    },
    delRegionByIndex(index, id) {
      this.formData.tableData.splice(index, 1);
      this.$refs.goodsDialogRef.deleteFn(index, id);
    },
    // 表单验证
    tableRules(row, scope) {
      // console.log(scope);
      return [
        { required: true, message: "调拨数量不能为空" },
        {
          pattern: /^\+?[1-9]\d*$/,
          message: "调拨数量必须为正整数",
          trigger: "blur",
        },
        {
          validator: (rule, value, callback) => {
            if (value > row.inventoryNumber) {
              callback("调拨数量不能超过库存数量");
            } else {
              callback();
            }
          },
        },
      ];
    },
    async getGoodsInfo(name) {
      // 校验仓库为必填
      if (name) {
        this.goodsName = name;
      }
      // 调接口，搜索列表
      if (this.goodsName === "")
        return this.$message.warning("请输入要搜索的内容");
      const res = await searchGoodsList({
        commodityName: this.goodsName,
        ...this.page,
      });
      if (res.code === 200) {
        this.gridData1 = res.data.list;
        this.page.pageNum = res.data.pageNum;
        this.page.pageSize = res.data.pageSize;
        this.page.total = res.data.total;
        console.log(res.data, "res.data");
        console.log(this.gridData1, "this.gridData1");
        // 1. 列表无数据，提示
        if (this.gridData1.length === 0) {
          this.$message.warning("未找到该商品");
          console.log("未找到该商品");
          return;
        } else {
          // 2. 列表有数据，弹窗展示列表
          console.log(this.gridData1, "有商品");
          this.$nextTick(() => {
            this.$refs.inputaldQty.blur();
            this.dialogVisible = true;
            this.defaultRowKey = 0;
            this.$refs.popTab.setCurrentRow(this.gridData1[this.defaultRowKey]);
            document.addEventListener('keyup', this.keyUp)
          })
        }
      }
    },
    keyUp(e) {
      let height = 47
      if (e.key === 'ArrowDown') {
        if (this.defaultRowKey == this.gridData1.length - 1) return;
        this.defaultRowKey++;
        this.$refs.popTab.setCurrentRow(this.gridData1[this.defaultRowKey]);
        this.$refs.popTab.bodyWrapper.scrollTop = (height * (this.defaultRowKey - 4));
      } else if (e.key === 'ArrowUp') {
        if (this.defaultRowKey == 0) return;
        this.defaultRowKey--;
        this.$refs.popTab.setCurrentRow(this.gridData1[this.defaultRowKey]);
        this.$refs.popTab.bodyWrapper.scrollTop = (height * (this.defaultRowKey - 4));
      } else if (e.key === 'Enter') {
        this.handleCurrentChanges(this.gridData1[this.defaultRowKey]);

      }
    },
    nextInput(i) {
      // 获取当前活动元素
      var activeElement = document.activeElement;
      document.querySelector('.remove-popover')?.remove();
      // 查找下一个可聚焦的元素
      var focusableElements = 'input:not([disabled])';
      var allFocusableElements = Array.prototype.slice.call(document.querySelectorAll(focusableElements), 0);
      var index = allFocusableElements.indexOf(activeElement);
      // 如果当前元素不在列表中，将其设置为第一个元素
      if (index === -1) {
        if (typeof i === 'number') {
          index = i;
        } else {
          index = 0;
        }
      }
      // 聚焦到下一个元素，如果已经是最后一个，则回到第一个
      var nextElementIndex = (index + 1) % allFocusableElements.length;
      allFocusableElements[nextElementIndex].focus();
    },
    cancelBtn() {
      this.closeTag("purchaseBack");
    },
    hiddenPop() {
      this.page.pageNum = 1;
      this.dialogVisible = false;
    },
    async handleCurrentChanges(val) {
      console.log(val, '表格高亮')
      this.$refs.ruleForm.validate(async (isOk) => {
        if (isOk) {
          console.log(isOk, "ok");
          // 调接口
          if (val) {
            const res = await getBatchList({
              commodityId: val.commodityId,
              allocationStore: this.sform.allocationStore,
            });
            if (res.code === 200) {
              // 1.有数据，打开弹窗
              // 1.1 判断数据是否为0
              this.gridData2 = res.data
              if (this.gridData2.length === 0) {
                this.$message.warning("未找到该商品入库记录");
                // 关闭popover
                return;
              }
              this.dialogVisible = false;
              console.log(res.data, "res.data");
              this.showDialog = true;
            } else {
              // 2.没有数据，提示
              // this.$message.warning('未找到该商品相关订单')
            }
          }
        } else {
          this.$message.warning("请先选择仓库和供应商");
        }
      });
    },
    commitFn(list) {
      console.log(list, "回显");
      let index = 2 + this.formData.tableData.length - 1;
      this.formData.tableData = list;
      this.formData.tableData.push({ name: "" });
      this.$nextTick(() => {
        this.nextInput(index);
      })
    },
    openPopover() {
      // 弹框展示时注册全局点击事件
      if (this.dialogVisible) {
        document.addEventListener("click", this.hidePopover, false);
      } else {
        document.removeEventListener("click", this.hidePopover, false);
      }
    },
    hidePopover(e) {
      // 全局点击事件，检测当前点击位置不包含弹框的元素，则隐藏弹框
      if (this.dialogVisible) {
        if (!this.$refs.myPopover?.$el.contains(e.target)) {
          this.dialogVisible = false;
        }
      } else {
        document.removeEventListener("click", this.hidePopover, false);
      }
    },
    // 获取条数改变
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.page.pageNum = 1;
      console.log(`每页 ${val} 条`);
      this.getGoodsInfo(this.goodsName);
    },
    // 获取页数改变
    handleCurrentChange(val) {
      this.page.pageNum = val;
      this.getGoodsInfo(this.goodsName);
    },
    async exportFn() {
      this.$confirm('确认导出数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const response = await exportAllocationList({
          id: this.detail.id
        })
        let res = null;
        if (response.data.type === "application/json") {
          const reader = new FileReader();  //创建一个FileReader实例
          reader.readAsText(response.data, 'utf-8'); //读取文件,结果用字符串形式表示
          reader.onload = () => {//读取完成后,**获取reader.result**
            res = JSON.parse(reader.result)
            if (res.code !== 200) {
              this.$message.error(res.message);
              return;
            }
          }
        } else {
          const fileName = decodeURIComponent(response.headers["content-disposition"].split(";")[1].split("''")[1]);
          FileSaver.saveAs(response.data, fileName);
        }
      })
    }
  },
};
</script>

<style lang="scss" scoped>
.flexContent {
  h3 {
    margin: 0;
    margin-bottom: 10px;
  }
}
</style>
